import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'dart:developer' as developer;

/// 后台系统通知助手
class BackgroundNotificationHelper {
  BackgroundNotificationHelper._();
  static final BackgroundNotificationHelper instance =
      BackgroundNotificationHelper._();

  final FlutterLocalNotificationsPlugin _plugin =
      FlutterLocalNotificationsPlugin();
  bool _initialized = false;

  static const AndroidNotificationChannel _channel = AndroidNotificationChannel(
    'background_message_channel',
    '后台消息提醒',
    description: '应用在后台时的即时消息提醒',
    importance: Importance.high,
    playSound: true,
  );

  final Map<String, List<int>> _userNotificationIds = {};

  Future<void> initialize() async {
    if (_initialized) return;
    const androidSettings = AndroidInitializationSettings(
      '@mipmap/ic_launcher',
    );
    const iosSettings = DarwinInitializationSettings(
      requestAlertPermission: true,
      requestBadgePermission: true,
      requestSoundPermission: true,
    );
    const settings = InitializationSettings(
      android: androidSettings,
      iOS: iosSettings,
    );

    await _plugin.initialize(
      settings,
      onDidReceiveNotificationResponse: _onNotificationTapped,
    );

    await _plugin
        .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin
        >()
        ?.createNotificationChannel(_channel);
    _initialized = true;
    developer.log('✅ 后台通知助手初始化完成');
  }

  Future<void> showChatNotification({
    required String senderPhone,
    int? friendId,
    required String senderName,
    required String senderAvatar,
    required String messageContent,
  }) async {
    await initialize();

    final payload = jsonEncode({
      'friendId': friendId,
      'friendPhone': senderPhone,
      'friendName': senderName,
      'friendAvatar': senderAvatar,
    });

    final notificationDetails = NotificationDetails(
      android: AndroidNotificationDetails(
        _channel.id,
        _channel.name,
        channelDescription: _channel.description,
        importance: Importance.high,
        priority: Priority.high,
        icon: '@mipmap/ic_launcher',
        styleInformation: BigTextStyleInformation(
          messageContent,
          contentTitle: senderName,
        ),
      ),
      iOS: const DarwinNotificationDetails(
        presentAlert: true,
        presentBadge: true,
        presentSound: true,
      ),
    );

    final notificationId = DateTime.now().millisecondsSinceEpoch.remainder(
      0x7fffffff,
    );

    await _plugin.show(
      notificationId,
      senderName,
      messageContent,
      notificationDetails,
      payload: payload,
    );

    _userNotificationIds
        .putIfAbsent(senderPhone, () => <int>[])
        .add(notificationId);

    developer.log('📳 后台系统通知已发送: $senderName');
  }

  Future<void> clearUserNotifications(String userId) async {
    final ids = _userNotificationIds.remove(userId);
    if (ids == null || ids.isEmpty) return;
    for (final id in ids) {
      await _plugin.cancel(id);
    }
  }

  void _onNotificationTapped(NotificationResponse response) {
    final payload = response.payload;
    if (payload == null || payload.isEmpty) {
      developer.log('⚠️ 后台通知 payload 为空');
      return;
    }
    try {
      final data = jsonDecode(payload) as Map<String, dynamic>;
      final friendPhone = data['friendPhone'] as String?;
      final friendId = data['friendId'] as int?;
      final friendName = data['friendName'] as String? ?? '未知用户';
      final friendAvatar = data['friendAvatar'] as String? ?? '';
      if (friendPhone == null || friendPhone.isEmpty) {
        developer.log('⚠️ 后台通知缺少好友手机号');
        return;
      }
      _navigateToChatPage(
        friendId: friendId,
        friendPhone: friendPhone,
        friendName: friendName,
        friendAvatar: friendAvatar,
      );
      clearUserNotifications(friendPhone);
    } catch (e) {
      developer.log('💥 解析后台通知 payload 失败: $e');
    }
  }

  void _navigateToChatPage({
    int? friendId,
    required String friendPhone,
    required String friendName,
    required String friendAvatar,
  }) {
    try {
      Get.toNamed(
        '/message_message_chat',
        arguments: {
          'friendId': friendId,
          'friendPhone': friendPhone,
          'friendName': friendName,
          'friendAvatar': friendAvatar,
        },
      );
    } catch (e) {
      developer.log('💥 后台通知跳转聊天页面失败: $e');
    }
  }
}
